/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-05-06 23:09:53
 * @LastEditors: DESKTOP-D0D7KKT\Administrator 18368095041@163.com
 * @LastEditTime: 2024-11-29 15:29:15
 * @FilePath: \vue3-uniapp\src\store\modules\app.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { generate } from '@ant-design/colors';

import { store } from '@/store';
import { useStorage } from '@/service/useStorage';

import { ColorConfig, type ThemeMode, camelToKebab } from './theme';

export const useAppStore = defineStore('app', () => {
    const {
        getThemeMode,
        setThemeMode: setThemeModeCache,
        getThemePrimary,
        setThemePrimary
    } = useStorage();
    const colorConfig = new ColorConfig();
    const theme = ref<ColorConfig>();
    const themeMode = ref<ThemeMode>(getThemeMode() || 'default');
    const cssVarObject = ref<Record<string, string>>({});

    const setTheme = (config: ColorConfig, needAppRestart = true) => {
        const keys = Reflect.ownKeys(
            config.color
        ) as (keyof ColorConfig['color'])[];
        const themeObject: ColorConfig = JSON.parse(JSON.stringify(config));
        // 本地存储主题色
        const themePrimary = themeObject.color.primary.default;
        setThemePrimary(themePrimary);

        keys.forEach((key) => {
            if (themeObject.color[key].dark === undefined) {
                themeObject.color[key].dark = generate(
                    themeObject.color[key].default,
                    {
                        theme: 'dark',
                        backgroundColor: themeObject.background.background.dark
                    }
                )[5];
            }
        });
        theme.value = themeObject;
        /* #ifdef APP-PLUS  */
        // app需重启才能生效，除非所有页面不用cssvar都用js的方式更改样式
        if (needAppRestart) {
            plus.runtime.restart();
        }
        /* #endif */
    };

    const setThemeMode = (mode: ThemeMode, needAppRestart = true) => {
        themeMode.value = mode;
        setThemeModeCache(mode);
        // /* #ifdef APP-PLUS  */
        if (needAppRestart) {
            plus.runtime.restart();
        }
        // /* #endif */
    };

    const handleThemeChange = () => {
        if (theme.value === undefined)
            throw new Error('[./store/modules/app]theme还未初始化');
        const themeColorKeys = Object.keys(
            theme.value.color
        ) as (keyof typeof theme.value.color)[];
        themeColorKeys.forEach((key) => {
            cssVarObject.value[`--c-${camelToKebab(key)}`] =
                theme.value!.color[key][themeMode.value]!;
        });
        const themeBackgroundKeys = Object.keys(
            theme.value.background
        ) as (keyof typeof theme.value.background)[];
        themeBackgroundKeys.forEach((key) => {
            cssVarObject.value[`--bg-${camelToKebab(key)}`] =
                theme.value!.background[key][themeMode.value]!;
        });
        themeColorKeys.forEach((key) => {
            cssVarObject.value[`--bg-${camelToKebab(key)}`] =
                theme.value!.color[key][themeMode.value]!;
        });
        const themeTextColorKeys = Object.keys(
            theme.value.textColor
        ) as (keyof typeof theme.value.textColor)[];
        themeTextColorKeys.forEach((key) => {
            cssVarObject.value[`--c-${camelToKebab(key)}`] =
                theme.value!.textColor[key][themeMode.value]!;
        });

        const themeTextKeys = Object.keys(
            theme.value.text
        ) as (keyof typeof theme.value.text)[];
        themeTextKeys.forEach((key) => {
            cssVarObject.value[`--text-${camelToKebab(key)}`] =
                theme.value!.text[key];
        });
    };

    const primaryColor = getThemePrimary();
    if (primaryColor) {
        colorConfig.color.primary.default = primaryColor;
    }
    setTheme(colorConfig, false);

    watchEffect(() => {
        if (themeMode.value && theme.value) {
            handleThemeChange();
            console.log(`全局样式变量：`, cssVarObject);
        }
    });
    return {
        theme,
        themeMode,
        cssVarObject,
        setTheme,
        setThemeMode
    };
});

// 手动提供给 useStore() 函数 pinia 实例
// https://pinia.vuejs.org/zh/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
export function useAppStoreHook() {
    return useAppStore(store);
}
